package com.project.card.ui;

import static com.project.card.util.UrlUtil.SERVER_URL;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.card.R;
import com.project.card.adapter.NewsAdapter;
import com.project.card.bean.NewsBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

// Uri uri = Uri.parse("https://www.baidu.com");
//Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//startActivity(intent);
public class HomeFragment extends Fragment {
    private ListView listView;
    private Button btn_switch;
    private ArrayList<NewsBean> newsList=new ArrayList<>();
    private boolean flag=true;
    private String regex="\\[(.*?)]";
    private JsonNode nodeSoc;
    private JsonNode nodeHea;

    public static final ObjectMapper JSONMAPPER = new ObjectMapper()
            .enable(JsonParser.Feature.IGNORE_UNDEFINED)
            .enable(JsonParser.Feature.ALLOW_COMMENTS)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


    /*
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    /*
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }*/


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =inflater.inflate(R.layout.fragment_home,container,false);
        listView=(ListView) view.findViewById(R.id.home_list);
        btn_switch=(Button)  view.findViewById(R.id.home_btn_switch);
        newsList.clear();

        OkHttpClient client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d("tnn","startf");
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("id","1");
                    Request request = new Request.Builder()
                            .url(SERVER_URL+"socnews/news")
                            .post(params.build())
                            .build();
                    Log.d("tnn","req");
                    Response response = client.newCall(request).execute();
                    Log.d("tnn","res");
                    String responseData = response.body().string();
                    nodeSoc =JSONMAPPER.readTree(responseData);
//                    nodeSoc.get("data").forEach(data -> {
//                        NewsBean temp = new NewsBean();
//                        temp.setTitle(data.get("title").asText());
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                        try {
//                            temp.setDate(sdf.parse(data.get("date").asText().substring(0,10)));
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                        newsList.add(temp);
//                    });
                    Log.d("tnn", responseData);
//            JSONArray jsonArray = new JSONArray(responseData);
//            for(int i=0;i<jsonArray.length();i++){
//                Log.d("title",""+jsonArray.getJSONObject(i).getString("title"));
//            }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d("tnn","startf");
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("id","1");
                    Request request = new Request.Builder()
                            .url(SERVER_URL+"heanews/news")
                            .post(params.build())
                            .build();
                    Log.d("tnn","req");
                    Response response = client.newCall(request).execute();
                    Log.d("tnn","res");
                    String responseData = response.body().string();
                    nodeHea =JSONMAPPER.readTree(responseData);
//                    nodeHea.get("data").forEach(data -> {
//                        NewsBean temp = new NewsBean();
//                        temp.setTitle(data.get("title").asText());
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                        try {
//                            temp.setDate(sdf.parse(data.get("date").asText().substring(0,10)));
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                        newsList.add(temp);
//                    });
                    Log.d("tnn", responseData);
//            JSONArray jsonArray = new JSONArray(responseData);
//            for(int i=0;i<jsonArray.length();i++){
//                Log.d("title",""+jsonArray.getJSONObject(i).getString("title"));
//            }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        //发送请求
        

//        newsList.add(new NewsBean("First_S",new Date(),R.drawable.ic_launcher_background));
//        newsList.add(new NewsBean("Second_S",new Date(),R.drawable.ic_launcher_background));
//        newsList.add(new NewsBean("Third_S",new Date(),R.drawable.ic_launcher_background));

        NewsAdapter newsAdapter=new NewsAdapter(getActivity().getApplicationContext(), R.layout.news_item,newsList);
        listView.setAdapter(newsAdapter);
        btn_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag=!flag;
                if(flag){
                    //S side
                    newsList.clear();
                    nodeSoc.get("data").forEach(data -> {
                        NewsBean temp = new NewsBean();
                        temp.setTitle(data.get("title").asText());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            temp.setDate(sdf.parse(data.get("date").asText().substring(0,10)));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        temp.setLink(data.get("url").asText());
                        newsList.add(temp);
                    });
//                    newsList.add(new NewsBean("First_S",new Date(),R.drawable.ic_launcher_background));
//                    newsList.add(new NewsBean("Second_S",new Date(),R.drawable.ic_launcher_background));
//                    newsList.add(new NewsBean("Third_S",new Date(),R.drawable.ic_launcher_background));
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Uri uri  = Uri.parse(newsList.get(i).getLink());
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        }
                    });
                    listView.setAdapter(newsAdapter);
                }else {
                    //H side
                    newsList.clear();
                    nodeHea.get("data").forEach(data -> {
                        NewsBean temp = new NewsBean();
                        temp.setTitle(data.get("title").asText());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            temp.setDate(sdf.parse(data.get("date").asText().substring(0,10)));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        temp.setLink(data.get("url").asText());
                        newsList.add(temp);
                    });
//                    newsList.add(new NewsBean("First_H",new Date(),R.drawable.ic_launcher_background));
//                    newsList.add(new NewsBean("Second_H",new Date(),R.drawable.ic_launcher_background));
//                    newsList.add(new NewsBean("Third_H",new Date(),R.drawable.ic_launcher_background));
                    
                    listView.setAdapter(newsAdapter);
//                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                            Toast.makeText(getContext(), "No application available to open URL", Toast.LENGTH_LONG).show();
//                            Uri uri = Uri.parse(newsList.get(i).getLink());
//                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                            startActivity(intent);
//                        }
//                    });
                }
            }
        });
//        for(int i=0;i<2;i++) {
//            newsBeans.add(new NewsBean(String.valueOf(i), new Date(), i));
//        }
        //lv.setAdapter(new NewsAdapter(getActivity(),newsBeans));
        return view;



    }

    public static String strInJson(String s){
        int idp = s.indexOf('[');
        int idq = s.indexOf(']');
        return s.substring(idp+1,idq-1);
    }
}